using System;
using System.Data;
using Edge.DAL.Common;
using NHibernate;

namespace Edge.DAL.Common.DALOperations
{
    class SaveDalOperation : IDalOperation
    {
        //        ISession session;
        ITransaction tx;
        bool commited = false;
        bool nested = false;
        private ISession session;
        private FlushMode? oldFlushMode;

        public SaveDalOperation(ISession session, FlushMode flushMode)
            : this(session)
        {
            if (session.FlushMode != flushMode)
            {
                oldFlushMode = session.FlushMode;
                session.FlushMode = flushMode;
            }
        }


        public SaveDalOperation(ISession session)
            : this(session, IsolationLevel.ReadCommitted)
        {

        }

        public SaveDalOperation(ISession session, IsolationLevel level)
        {

            // TODO check nested transactions!!!

            this.session = session;

            nested = session.Transaction.IsActive;


            if (!nested)
                tx = session.BeginTransaction(level);
            else
                tx = session.Transaction;

        }

        public void Commit()
        {
            try
            {
                if (!nested)
                    tx.Commit();

                if (oldFlushMode != null)
                    session.FlushMode = (FlushMode)oldFlushMode;

                commited = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public void Dispose()
        {
            if (!commited)
            {
                if (!tx.WasRolledBack)
                    tx.Rollback();
            }

        }
    }
}